package com.linked.basemanage.file.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.linked.basemanage.config.MinioProp;
import com.linked.basemanage.file.bean.po.FileInfoPO;
import com.linked.basemanage.file.service.IFileHandleService;
import com.linked.basemanage.util.MinioUtils;
import com.linked.universal.common.LinkedProject;
import com.linked.universal.common.LinkedPrompt;
import com.linked.universal.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@RestController
@Slf4j
@RequestMapping("/file")
public class FileHandleController {

    private final IFileHandleService fileHandleService;

    private final ObjectMapper mapper;

    private final MinioUtils minioUtils;

    private final MinioProp minioProp;

    public FileHandleController(IFileHandleService fileHandleService, ObjectMapper mapper,
                                MinioUtils minioUtils, MinioProp minioProp) {
        this.fileHandleService = fileHandleService;
        this.mapper = mapper;
        this.minioUtils = minioUtils;
        this.minioProp = minioProp;
    }

    @PostMapping("/uploadFile")
    Result uploadFile(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        String minioUri = null;
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        try (InputStream inputStream = file.getInputStream()) {
            minioUri = minioUtils.uploadFile(inputStream, minioProp.getBucketName(), "tempFiles", suffix);
        } catch (Exception e) {
            log.error("上传文件异常！", e);
            return Result.error(LinkedPrompt.ERROR_MESSAGE);
        }
        FileInfoPO fileInfo = new FileInfoPO();
        try {
            fileInfo.setOriginName(fileName);
            fileInfo.setFileDir(minioUri);
            fileInfo.setFileGroup(minioProp.getBucketName());
            fileInfo.setFileType(suffix);
            fileInfo.setBelongProject(LinkedProject.baseManage);
            fileInfo.setFileSize(file.getSize() + "");
            fileInfo.setContentType(file.getContentType());
            fileHandleService.saveFileInfo(fileInfo);
        } catch (Exception e) {
            log.error("保存文件业务信息异常！", e);
            return Result.error(LinkedPrompt.ERROR_MESSAGE);
        }
        return Result.success(fileInfo.getFileId());
    }
}
